#!/usr/bin/python
import sqlite3
import os
import cgi
import cgitb
from Cookie import SimpleCookie
from pygallib import userlib
from pygallib import usersession
from pygallib import layoutlib
from pygallib import albumlib
from pygallib import picturelib

cgitb.enable()

logged_in = usersession.logged_in()
fields = cgi.FieldStorage()
conn = None
album = None
session_user = None
if logged_in:
  session_user = usersession.get_session_user()

if "albumid" in fields:
  bad_input = False
  try:
    album_id = int(fields["albumid"].value)
    if "picid" not in fields:
      pic_id = -1
    else:
      pic_id = int(fields["picid"].value)
  except ValueError:
    bad_input = True 
  if not bad_input:
    album = albumlib.get_album(album_id)
    # Get user who created album
    user = userlib.get_user_by_id(album["user_id"])
    user_authorized = False
    if logged_in:
      if (session_user["user_id"] == user["user_id"] or
          session_user["root"] == 1):
        user_authorized = True
    # Get album information
    album_is_public = True if (int(album["is_public"]) == 1) else False
    # Read all pictures in album
    (picture_cur, conn) = albumlib.get_album_pictures(album_id)
    # Find current picture in slideshow
    pictures = picture_cur.fetchmany(picture_cur.rowcount)
    if len(pictures) > 0:
      first_picture = pictures[0]
      last_picture = pictures[-1]
      current_picture = first_picture
      current_index = 0
      prev_picture = first_picture
      next_picture = first_picture
      for i in range(0, len(pictures)): 
        if pictures[i]["picture_id"] == pic_id:
          current_index = i
          break
      current_picture = pictures[current_index]
      prev_picture = pictures[current_index - 1]
      if current_index + 1 == len(pictures):
        next_picture = pictures[0]
      else:
        next_picture = pictures[current_index + 1]

headers = {}
headers["Content-type"] = "text/html"
layoutlib.print_http_headers(headers)
layoutlib.print_page_open("PyGallery - Album")
print("<body>")
menu = []
menu.append(("Home", "gallery.cgi"))

if album is None:
  layoutlib.print_page_header(menu, session_user)
  print('<div id="page_body">')
  print('<p>No album selected. Pick one <a href="gallery.cgi">here</a>.</p>')
  print('</div>')
else:
  layoutlib.print_page_header(menu, session_user)
  print('<div id="page_body">')
  if album_is_public or user_authorized:
    # Print header
    print('<h1>%s <span>by %s</span></h1>' % (album["name"], user["username"]))
    print('<p><a id="go_back" href="album.cgi?id=' + 
        str(album_id) + '">Go back to album</a></p>')
    if len(pictures) > 0:
      print('<div id="slideshow_container" class="clearfix">')
      print("""
      <div id="prev_picture">
        <a href="slideshow.cgi?albumid=%d&picid=%d">
          Prev
          <img width="100" src="/PictureShare/users/%s/albumthumb%d/%s" />
        </a>
      </div>
      """ % (album_id, prev_picture["picture_id"], user["username"],
        album_id, prev_picture["file_name"]))
      print("""
      <div id="current_picture">
        <a href="slideshow.cgi?albumid=%d&picid=%d">
          <img width="450" src="/PictureShare/users/%s/album%d/%s" />
        </a>
        <p>%s</p>
      </div>
      """ % (album_id, current_picture["picture_id"], user["username"],
        album_id, current_picture["file_name"], current_picture["label"]))
      print("""
      <div id="next_picture">
        <a href="slideshow.cgi?albumid=%d&picid=%d">
          Next
          <img width="100" src="/PictureShare/users/%s/albumthumb%d/%s" />
        </a>
      </div>
      """ % (album_id, next_picture["picture_id"], user["username"],
        album_id, next_picture["file_name"]))
      print('</div>')
  elif (not int(album["is_public"]) == 1) and (not user_authorized):
    print("This is a private album.")
  print('</div>')
if conn:
  conn.close()
layoutlib.print_page_close()
